// Makes use of the citro2d example
#include <citro2d.h>
#include "sprites.h"

static C2D_SpriteSheet sprite_sheet;

// Borrowed from new-hbmenu with a minor adjustment.
// with permission as seen below
// <fincs> You have my permission to take code from new-hbmenu and use it in a project licensed under MIT
static bool konamiCheck(u32 down)
{
	static const u32 params[] = { KEY_UP, KEY_UP, KEY_DOWN, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_LEFT, KEY_RIGHT, KEY_B, KEY_A };
	static u32 state, timeout;

	if (down & params[state])
	{
		state++;
		timeout = 30;
		if (state == sizeof(params)/sizeof(params[0]))
		{
			state = 0;
			return true;
		}
	}

	if (timeout && !--timeout)
		state = 0;

	return false;
}

int main() {
    // Init libs
    romfsInit();
    gfxInitDefault();
    C3D_Init(C3D_DEFAULT_CMDBUF_SIZE);
    C2D_Init(C2D_DEFAULT_MAX_OBJECTS);
    C2D_Prepare();
    
    C3D_RenderTarget* top = C2D_CreateScreenTarget(GFX_TOP, GFX_LEFT);
    C3D_RenderTarget* bottom = C2D_CreateScreenTarget(GFX_BOTTOM, GFX_LEFT);

    sprite_sheet = C2D_SpriteSheetLoad("romfs:/gfx/sprites.t3x");
    if (!sprite_sheet) svcBreak(USERBREAK_PANIC);
    bool konami_code = false;

    while (aptMainLoop())
    {
        hidScanInput();

        u32 kDown = hidKeysDown();
        if (kDown & KEY_START)
            break;

        if (konami_code == false)
            konami_code = konamiCheck(kDown);

        // Render images
        C3D_FrameBegin(C3D_FRAME_SYNCDRAW);
        C2D_TargetClear(top, C2D_Color32(255, 255, 255, 0));
        C2D_TargetClear(bottom, C2D_Color32(255, 255, 255, 0));
        C2D_SceneBegin(top);
        if (konami_code == true)
            C2D_DrawImageAt(C2D_SpriteSheetGetImage(sprite_sheet, sprites_eastertop_idx), 0, 0, 0.6f, NULL, 1.0f, 1.0f);
        else
            C2D_DrawImageAt(C2D_SpriteSheetGetImage(sprite_sheet, sprites_topscreen_idx), 0, 0, 0.6f, NULL, 1.0f, 1.0f);
        C2D_SceneBegin(bottom);
        if (konami_code == true)
            C2D_DrawImageAt(C2D_SpriteSheetGetImage(sprite_sheet, sprites_easterbottom_idx), 0, 0, 0.6f, NULL, 1.0f, 1.0f);
        else
            C2D_DrawImageAt(C2D_SpriteSheetGetImage(sprite_sheet, sprites_bottomscreen_idx), 0, 0, 0.6f, NULL, 1.0f, 1.0f);
        C3D_FrameEnd(0);
    }

    C2D_SpriteSheetFree(sprite_sheet);
    C2D_Fini();
    C3D_Fini();
    gfxExit();
    romfsExit();
    return 0;
}